<script setup>
import { ref } from 'vue';
import { useGlobalAbility } from '@/mixins/getGlobalAbility.js';
import { setAvatar } from '@/api/common.js';

const { $message } = useGlobalAbility();
const emit = defineEmits(['close', 'setImg']);

// 头像地址
const imgUrl = ref('');
// 头像上传
const fileName = ref(''); // 上传文件的文件名称
const fileUploadRef = ref(null); // 上传组件
let uploadFile = {}; // 上传的文件
function imgUpload(file) {
  const { size } = file.file;
  if (size > 1024 * 1024) {
    $message.error('图片大小不能超过 1M');
    return false;
  }
  // 创建Image对象，用于获取图片尺寸
  const img = new Image();
  const url = URL.createObjectURL(file.file);
  img.src = url;
  img.onload = function () {
    if (img.width !== img.height) {
      $message.error('图片尺寸比例不是1:1');
      return false;
    }
    imgUrl.value = url;
    fileName.value = file.file.name;
    uploadFile = file.file;
  };
  fileUploadRef.value.clearFiles();
}
async function sureHandle() {
  const formData = new FormData();
  formData.append('avatarfile', uploadFile, fileName.value);
  const returnData = await setAvatar(formData);
  if (returnData?.code === 200) {
    $message.success('操作成功');
    emit('setImg', returnData.avatar);
  } else {
    $message.error(returnData?.msg);
  }
}
</script>

<template>
  <el-dialog
    :model-value="true"
    :show-close="false"
    class="add-tpl-dialog set-head-img-dialog"
    @close="emit('close')"
  >
    <template #title>
      <div class="title">上传头像</div>
    </template>
    <div class="content">
      <div class="left-content">
        <div class="img-box">
          <img
            src="@/assets/images/setHeadImgDialog/imgBackground.png"
            alt=""
            class="background-img"
          />
          <img :src="imgUrl" alt="" class="upload-img" v-show="imgUrl" />
        </div>
        <div class="hint-box">
          图片大小比例1：1，JPG/PNG，1M以内。头像修改后，部分页面次日生效。
        </div>
      </div>
      <div class="right-content">
        <div class="preview-box">
          <img :src="imgUrl" alt="" class="preview-img" v-show="imgUrl" />
        </div>
        <div class="hint-box">头像预览</div>
        <el-upload
          accept=".jpg, .png"
          :http-request="imgUpload"
          :show-file-list="false"
          :limit="1"
          class="img-upload"
          ref="fileUploadRef"
        >
          <div class="upload-btn">上传头像</div>
        </el-upload>
      </div>
    </div>
    <div class="footer-box">
      <div class="cancel-btn btn" @click="emit('close')">取消</div>
      <div class="sure-btn btn" @click="sureHandle">确定</div>
    </div>
  </el-dialog>
</template>

<style scoped lang="less">
@import 'setHeadImg.less';
</style>
